package com.shunan.miaosha.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shunan.miaosha.beans.Users;
import com.shunan.miaosha.exception.CanNotFindUserException;
import com.shunan.miaosha.redis.RedisService;
import com.shunan.miaosha.redis.UserKeyPrefix;
import com.shunan.miaosha.result.CodeMsg;
import com.shunan.miaosha.result.Result;
import com.shunan.miaosha.service.UserService;
import com.shunan.miaosha.utils.UUIDUtil;
import com.shunan.miaosha.vo.UserVo;

@Controller
@RequestMapping("/login")
public class LoginController {
	
	@Autowired	
	private UserService userService;
	@Autowired
	private RedisService redisService;
	
	
	@RequestMapping("/do_login")
	@ResponseBody
	public Result<String> do_login(@Valid UserVo userVo,HttpServletResponse response){
		Users u=userService.findUser(userVo.getName(), userVo.getPassword());
		if(u==null){
			throw new CanNotFindUserException();
		}
		String token = UUIDUtil.uuid();
		redisService.set(UserKeyPrefix.user, token, u);
		Cookie cookie=new Cookie("token",token);
		cookie.setMaxAge(UserKeyPrefix.user.expireSeconds());
		cookie.setPath("/");
		response.addCookie(cookie);
		
		return Result.success("登录成功");
	}
	
	@RequestMapping("/to_login")
	public String to_login(){
		
		return "login";
	}
	
	@RequestMapping("/login/{id}")
	@ResponseBody
	public Result<String> login(@PathVariable("id") String id){
		Users u=userService.findUserByID(Integer.parseInt( id ));
		if(u!=null){			
			return Result.success("欢迎用户"+u.getName());
		}
		return Result.error(CodeMsg.NO_USER);
	}
}
